package com.vip.seata.at.business.tcc.action;

import com.vip.seata.at.business.tcc.RedissonUtils;
import io.seata.core.context.RootContext;
import io.seata.rm.tcc.api.BusinessActionContext;
import io.seata.rm.tcc.api.BusinessActionContextParameter;
import io.seata.rm.tcc.api.LocalTCC;
import io.seata.rm.tcc.api.TwoPhaseBusinessAction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.vip.seata.at.business.util.DateHelper;

import java.util.Date;

@Slf4j
@Service
@LocalTCC
public class OrderActionImpl implements OrderAction {
    String key = "seata:tcc:order_action";

    @Override
    @TwoPhaseBusinessAction(name = "createOrder", commitMethod = "commit", rollbackMethod = "cancel",useTCCFence = true)
    public Object createOrder(BusinessActionContext context,
                              @BusinessActionContextParameter(paramName = "userId") String userId,
                              @BusinessActionContextParameter(paramName = "code") String code,
                              Long count) throws Exception {
        String value = "try"+ DateHelper.formatStandardMILLI(new Date());
        log.info("try xid:{},key:{},value:{}",RootContext.getXID(),key,value);
        RedissonUtils.update(key,value);
        return null;
    }

    @Override
    public boolean commit(BusinessActionContext actionContext) throws Exception {
        String value = "commit"+ DateHelper.formatStandardMILLI(new Date());
        log.info("commit xid:{},key:{},value:{}",actionContext.getXid(),key,value);
        RedissonUtils.update(key,value);
        return true;
    }

    @Override
    public boolean cancel(BusinessActionContext actionContext) throws Exception {
        String value = "rollback"+ DateHelper.formatStandardMILLI(new Date());
        // TCC resource rollback result : true, xid: 172.17.0.2:8091:18560801480667143, branchId: 18560801480667144, resourceId: createOrder
        // xid:null,key:order_action,value:cancel2024-07-25 02:03:10.752
        log.info("cancel xid:{},key:{},value:{}",actionContext.getXid(),key,value);
        RedissonUtils.update(key,value);
        return true;
    }
}
